<template>
    <div class="default-main">
        <div class="ba-table-box">
            <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
            <div class="tabs-header">
                <el-tabs v-model="activeName" type="card" class="file-tabs" @tab-click="handleClick">
                    <el-tab-pane :label="label" :name="name" v-for="(label, name) in categoryList" :key="name"></el-tab-pane>
                </el-tabs>
                <div style="margin-left: 12px">
                    <el-dropdown placement="bottom" trigger="click" size="large">
                        <el-button size="large" type="primary">
                            <el-icon style="vertical-align: middle">
                                <Filter />
                            </el-icon>
                            <span style="vertical-align: middle"> 类型筛选 </span>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="(label, name) in filterList" :key="name" @click="handleFilterClick(name)">{{
                                    label
                                }}</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>

            <!-- 表格顶部菜单 -->
            <TableHeader
                :buttons="['refresh', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                :quick-search-placeholder="t('Quick search placeholder', { fields: t('utils.Original name') })"
            >
                <div style="margin-left: 12px">
                    <el-button type="success" @click="handleAddClick">
                        <el-icon style="vertical-align: middle">
                            <Plus />
                        </el-icon>
                        <span style="vertical-align: middle"> 添加 </span>
                    </el-button>
                </div>
                <div style="margin-left: 12px">
                    <el-dropdown trigger="click">
                        <el-button type="primary" :disabled="!enableBatchOpt">
                            <el-icon style="vertical-align: middle">
                                <Right />
                            </el-icon>
                            <span style="vertical-align: middle"> 归类 </span>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item
                                    v-for="(label, name) in categoryList"
                                    :key="name" @click="handleCategoryClick(name)">
                                    {{ label }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </TableHeader>

            <!-- 表格 -->
            <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
            <Table ref="tableRef" />

            <!-- 编辑和新增表单 -->
            <PopupForm ref="formRef" />
            <AddForm ref="addFormRef" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, useTemplateRef, ref, computed } from 'vue'
import PopupForm from './popupForm.vue'
import AddForm from './addForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import baTableClass from '/@/utils/baTable'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import { fullUrl } from '/@/utils/common'
import type { TabsPaneContext } from 'element-plus'
import { Filter, Right, Plus } from '@element-plus/icons-vue'
import { setAttachmentCategory } from '/@/api/backend/routine/attachment'

defineOptions({
    name: 'routine/attachment',
})
const categoryList = ref({
    '': '全部',
})

const filterList: anyObj = ref({
    '': '全部',
})

const activeName = ref('')
const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const formRef = useTemplateRef('formRef')
const addFormRef = useTemplateRef('addFormRef')


const optBtn = defaultOptButtons(['edit', 'delete'])
optBtn[1].popconfirm!.title = '文件和记录将同时删除，是否确认删除？'

const api = new baTableApi('general/attachment/')
const baTable = new baTableClass(
    api,
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('Id'), prop: 'id', align: 'center', operator: '=', operatorPlaceholder: t('Id'), width: 70 },
            {
                label: '类别',
                prop: 'category',
                align: 'center',
                render: 'tag',
                operator: 'IN',
                replaceValue: categoryList,
            },
            {
                label: '预览',
                prop: 'url',
                align: 'center',
                render: 'image',
                operator: false,
                formatter: (row: TableRow, column: TableColumn, cellValue: string) => {
                    return fullUrl(cellValue)
                },
            },
            {
                label: '文件名',
                prop: 'filename',
                align: 'center',
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: '文件大小',
                prop: 'filesize',
                align: 'center',
                formatter: (row: TableRow, column: TableColumn, cellValue: string) => {
                    const size = parseFloat(cellValue)
                    const i = Math.floor(Math.log(size) / Math.log(1024))
                    return (size / Math.pow(1024, i)).toFixed(i < 1 ? 0 : 2) + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i]
                },
                operator: 'RANGE',
                sortable: 'custom',
                operatorPlaceholder: 'bytes',
            },
            {
                label: '宽度',
                prop: 'imagewidth',
                align: 'center',
                operator: 'LIKE',
                showOverflowTooltip: true,
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: '宽度',
                prop: 'imageheight',
                align: 'center',
                operator: 'LIKE',
                showOverflowTooltip: true,
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: '图片类型',
                prop: 'imagetype',
                align: 'center',
                width: 150,
                operator: 'RANGE',
                sortable: 'custom',
            },
            {
                label: '存储引擎',
                prop: 'storage',
                align: 'center',
                showOverflowTooltip: true,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: 'Mime类型',
                prop: 'mimetype',
                align: 'center',
                width: 100,
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },
            {
                label: '上传时间',
                prop: 'createtime',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                width: 160,
            },
            {
                label: t('Operate'),
                align: 'center',
                width: '100',
                render: 'buttons',
                buttons: optBtn,
                operator: false,
            },
        ],
        defaultOrder: { prop: 'createtime', order: 'desc' },
    },
    {},
    {},
    {
        getEditData({ res }) {
            if (res && res.data) {
                const tempResult = Object.entries(categoryList.value).map(([k, v]) => ({
                    value: k, // 原对象的键作为新对象的 key 字段
                    label: v, // 原对象的值作为新对象的 value 字段
                }))
                formRef.value!.categoryList = tempResult
                baTable.form.items = res.data
                baTable.form.items.createtime = baTable.form.items.createtime * 1000
            }
        },
        getData({ res }) {
            if (res && res.data) {
                categoryList.value = { ...categoryList.value, ...res.data.categoryList }
                filterList.value = { ...filterList.value, ...res.data.mimetypeList }
            }
        },
    }
)

const enableBatchOpt = computed(() => (baTable.table.selection!.length > 0 ? true : false))

// 上传文件
const handleAddClick = () => {
    const tempResult = Object.entries(categoryList.value).map(([k, v]) => ({
        value: k, // 原对象的键作为新对象的 key 字段
        label: v, // 原对象的值作为新对象的 value 字段
    }))
    addFormRef.value!.categoryList = tempResult
    addFormRef.value!.onOpen()
}

// 设置文件类别
const handleCategoryClick = (name: string) => {
    const ids = baTable.table.selection!.map((item: TableRow) => item.id)
    setAttachmentCategory({
        category: name,
        ids: ids.join(','),
    }).then((res) => {
        if (res && res.code == 1) {
            baTable.onTableAction('com-search', {})
        }
    })
}

// 点击分类标签切换查询条件
const handleClick = (tab: TabsPaneContext, event: Event) => {
    baTable.comSearch.form.category = tab.props.name
    baTable.onTableAction('com-search', {})
}

// 点击文件类型标签切换查询条件
const handleFilterClick = (name: string) => {
    baTable.comSearch.form.mimetype = name
    baTable.onTableAction('com-search', {})
}

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getData()?.then(() => {
        baTable.initSort()
    })
})
</script>

<style scoped lang="scss">
.tabs-header {
    display: flex;
    justify-content: space-between;
}

.table-header-operate {
    margin-left: 12px;
}
.table-header-operate-text {
    margin-left: 6px;
}

.file-tabs :deep(.el-tabs__header) {
    border-bottom: none;
    margin-bottom: 0;
}
.file-tabs :deep(.is-active) {
    background-color: #fff;
}
</style>
